<template>
  <div class="h-panel">
    <div class="h-panel-bar">
      <Row :space="10">
        <Cell :width="12">
          <Cell :width="12">
            <div class="h-input-group">
              <Select v-model="collectionId" :datas="collectionList" @change="collectionChange"></Select>
              <Space :width="10" />
              <Button color="yellow"
                @click="() => { this.collectionOpend = true; this.collectionName = '' }">新增集合</Button>
              <Space :width="10" />
              <Button color="red" @click="collectionDelete" v-show="collectionId != ''">删除</Button>
            </div>
          </Cell>
        </Cell>
        <Cell :width="12">
          <Cell :width="10">
            <div class="h-input-group">
              <Button @click="locadData" icon="h-icon-refresh" no-border></Button>
              <Select v-model="filename" :datas="filenameList" @change="locadData" :of="collectionId"></Select>
            </div>
          </Cell>
          <Cell :width="14">
            <Space :width="10" />
            <Button color="primary" @click="add">新增文档</Button>
            <Space :width="10" />
            <Button @click="attachmentUpload" color="blue" v-show="collectionId != ''">上传文档</Button>
            <Space :width="10" />
            <Button color="red" @click="deleteFilename" v-show="collectionId != '' && filename != ''">删除</Button>
            <Space :width="10" />
          </Cell>
        </Cell>
      </Row>
    </div>
    <div class="h-panel-body bottom-line">
      <Table :datas="datas">
        <TableItem title="集合名称" prop="collectionName" :width="200" />
        <TableItem title="文件名称" prop="filename" :width="350" />
        <TableItem title="文档内容" prop="document" :format="dataFormat" />
        <TableItem title="操作" :width="200" fixed="right">
          <template #default="{ data }">
            <span class="link" @click="edit(data)">编辑</span>
            <Space :width="10" />
            <span class="link" @click="remove(data)">删除</span>
          </template>
        </TableItem>
      </Table>
    </div>
    <div class="h-panel-bar">
      <Pagination v-model="page" :total="page.total" @change="locadData" />
    </div>
    <Modal v-model="collectionOpend" :closeOnMask="false" :hasCloseIcon="true" :hasDivider="true">
      <template #header>新增集合</template>
      <Form>
        <FormItem label="集合名称">
          <Input type="text" v-model="collectionName" placeholder="集合名称英文" />
        </FormItem>
        <FormItem label="是否共享" prop="isOpen">
          <Radio v-model="isOpen" :datas="isOpenData"></Radio>
        </FormItem>
      </Form>
      <template #footer>
        <Button color="blue" @click="collectionAdd">确认</Button>
        <Button @click="collectionOpend = false">关闭</Button>
      </template>
    </Modal>

    <Modal v-model="editOpend" :closeOnMask="false" :hasCloseIcon="false" :hasDivider="true" :draggable="true">
      <template #header>文档管理</template>
      <Form :rules="validationRules" showErrorTip="true" mode="twocolumn">
        <FormItem label="是否共享" prop="isOpen">
          <Radio v-model="formModel.isOpen" :datas="isOpenData"></Radio>
        </FormItem>
        <FormItem label="所属集合">
          <Select v-model="formModel.collectionId" :datas="collectionList"></Select>
        </FormItem>
        <FormItem label="文件名称" prop="filename">
          <Input type="text" v-model="formModel.filename" />
        </FormItem>
        <FormItem label="绑定函数">
          <Select v-model="formModel.funcId" :datas="funcList"></Select>
        </FormItem>
        <FormItem label="业务数据" single>
          <Textarea type="text" v-model="formModel.metadata" rows="2" placeholder="JSON格式字符" style="width: 1000px;" />
        </FormItem>
        <FormItem label="文档内容" single>
          <Textarea type="text" v-model="formModel.document" rows="15" style="width: 1000px;" />
        </FormItem>
      </Form>
      <template #footer>
        <Button color="blue" @click="saveOrUpdate">确认</Button>
        <Button @click="editOpend = false">关闭</Button>
      </template>
    </Modal>

    <paas-upload-modal :url="'/ollamaembedding/uploads/' + this.collectionName" title="知识库文件上传" ref="upload"
      name="files" multiple="true" success="locadData"></paas-upload-modal>

  </div>
</template>

<script>
import { confirm, message } from 'heyui';

export default {
  mounted() {
    this.$bus.on("locadData", () => {
      this.locadData();
    });
    this.locadData();
    this.getCollectionList();
    this.getFuncList();
  },
  created() {
  },
  data() {
    return {
      isOpen: "0",
      isOpenData: [{ "value": "1", "label": "是" }, { "value": "0", "label": "否" }],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      formModel: {
        metadata: "{}"
      },
      editOpend: false,
      collectionOpend: false,
      collectionList: [],
      collectionId: "",
      collectionName: "",
      filenameList: [],
      funcList: [],
      filename: "",
      datas: [],
      validationRules: ["filename"],
    };
  },
  methods: {
    dataFormat(value) {
      if (value.length > 50) {
        return value.substring(0, 50) + "...";
      }
      return value;
    },
    locadData(p) {
      if (!!p) {
        this.page = p;
      }
      this.$post("/ollamaembedding/page", {
        page: { current: this.page.page, size: this.page.size },
        filename: this.filename,
        collectionId: this.collectionId,
      }).then(res => {
        if (res.data == null) {
          this.page.total = 0;
          return;
        }
        if (res.data.code != this.$success && res.msg != null) {
          message.error(res.msg);
          return;
        }
        if (!!res.data.data) {
          if (res.data.data.rows != null) {
            this.datas = res.data.data.rows;
          } else {
            this.datas = [];
          }
          this.page.total = res.data.data.total;
          return;
        } else {
          this.datas = [];
          this.page.total = 0;
        }
      });
    },
    saveOrUpdate() {
      if (!!this.formModel.uuid) {
        this.edit()
      } else {
        this.add();
      }
    },
    add() {
      if (!this.editOpend) {
        var model = this.datas[0];
        this.editOpend = true;
        this.formModel = {
          filename: model?.filename,
          tenantId: model?.tenantId,
          collectionId: model?.collectionId,
          metadata: model?.metadata,
          funcId: model?.funcId,
        };
        return;
      }
      if (!this.formModel.collectionId) {
        message.warn("所属集合不能为空");
        return;
      }
      if (!this.formModel.filename) {
        message.warn("文件名称不能为空");
        return;
      }
      if (!this.formModel.document) {
        message.warn("文档内容不能为空");
        return;
      }
      var data = Object.assign({ ...this.formModel }, { metadata: JSON.parse(this.formModel.metadata) });
      this.$post("/ollamaembedding", data).then(res => {
        if (res.data.code == this.$success) {
          this.editOpend = false;
          this.formModel = {};
          this.locadData();
        }
      });
    },
    edit(data) {
      if (!this.editOpend) {
        this.formModel = data;
        this.editOpend = true;
        return;
      }
      var data = Object.assign({ ...this.formModel }, { metadata: JSON.parse(this.formModel.metadata) });
      this.$put("/ollamaembedding/edit", data).then(res => {
        if (res.data.code == this.$success) {
          this.editOpend = false;
          this.formModel = {};
          this.locadData();
        }
      });
    },
    remove(data) {
      confirm({
        content: '确定删除？',
        onConfirm: () => {
          this.$delete("/ollamaembedding/" + data.uuid).then(res => {
            if (res.data.code == this.$success) {
              this.locadData();
            }
          });
        }
      });
    },
    deleteFilename() {
      if (!this.collectionId) {
        message.info("请先选择集合");
        return;
      }
      confirm({
        content: '确定删除？',
        onConfirm: () => {
          this.$post("/ollamaembedding/deleteFilename?collectionId=" + this.collectionId + "&filename=" + this.filename).then(res => {
            if (res.data.code == this.$success) {
              this.getCollectionList();
              this.getFilenameList();
              this.locadData();
            }
          });
        }
      });
    },

    getFilenameList() {
      this.$post("/ollamaembedding/list", { vars: { "a.collection_id": this.collectionId }, page: { current: 1, size: 1000 } }).then(res => {
        if (res.data.code == this.$success) {
          this.filenameList = res.data.data.rows;
        } else {
          message.error(res.data.msg);
        }
      })
    },
    getFuncList() {
      this.$post("/ollamafunctions/list", { page: { current: 1, size: 1000 } }).then(res => {
        if (res.data.code == this.$success) {
          this.funcList = res.data.data.rows;
          console.log(this.funcList)
        } else {
          message.error(res.data.msg);
        }
      })
    },
    getCollectionList() {
      this.$post("/ollamacollection/list", { page: { current: 1, size: 1000 } }).then(res => {
        if (res.data.code == this.$success) {
          this.collectionList = res.data.data.rows;
        } else {
          message.error(res.data.msg);
        }
      })
    },
    collectionChange(data) {
      this.collectionName = data.label;
      this.filenameList = [];
      this.getFilenameList();
      this.locadData();
    },
    collectionAdd() {
      if (!this.collectionName) {
        message.warn("集合名称不能为空");
        return;
      }
      this.$post("/ollamacollection", { name: this.collectionName, isOpen: this.isOpen }).then(res => {
        if (res.data.code == this.$success) {
          message.info(res.data.msg);
          this.collectionOpend = false;
          this.getCollectionList();
        }
      });
    },
    collectionDelete() {
      if (!this.collectionId) {
        message.warn("选择要删除的知识库集合");
        return;
      }
      confirm({
        content: '确定删除？',
        onConfirm: () => {
          this.$delete("/ollamacollection/" + this.collectionId).then(res => {
            if (res.data.code == this.$success) {
              this.getCollectionList();
              this.getFilenameList();
              this.locadData();
            }
          });
        }
      });
    },
    attachmentUpload() {
      this.$refs.upload.show()
    },
  },
};
</script>